class Solution:
    def longestValidParentheses(self, s: str) -> int:
        stk = []
        res, start = 0, -1
        for i in range(len(s)):
            if s[i] == '(':
                stk.append(i)
            else:
                if len(stk) > 0:
                    stk.pop()
                    if len(stk) > 0:
                        res = max(res, i - stk[-1])
                    else:
                        res = max(res, i - start)
                else:
                    start = i
        return res


s = ")()())"
print(Solution().longestValidParentheses(s))